package blockchain

import (
	"bytes"
	"crypto/sha256"
	"goblockchain/utils"
	"time"
)

type Block struct {
	Data      []byte
	Hash      []byte
	PrevHash  []byte
	Timestamp int64
	Nonce 	  int64
	Target	  []byte
}

func (b *Block) SetHash() {
	info := bytes.Join([][]byte{utils.ToHexInt(b.Timestamp), b.PrevHash, b.Target, utils.ToHexInt(b.Nonce), b.Data}, []byte{})
	hash := sha256.Sum256(info)
	b.Hash = hash[:]
}

func CreateBlock(data, prevHash []byte) *Block {
	block := Block{
		PrevHash  : prevHash,
		Data      : data,
		Hash      : []byte{},
		Timestamp : time.Now().Unix(),
		Nonce     : 0,
		Target    : []byte{},
	}
	block.Target = block.GetTarget()
	block.Nonce = block.FindNonce()
	block.SetHash()
	return &block
}

func GenesisBlock() *Block {
	genesisWords := "Hello, blockchain!"
	return CreateBlock([]byte(genesisWords), []byte{})
}

